//
//  LMCountDownButton.m
//  BusinessBlockChain
//
//  Created by shien_ios1 on 2018/7/18.
//  Copyright © 2018年 lairui. All rights reserved.
//

#import "LMCountDownButton.h"

static NSUInteger const totalSecond = 60;

@interface LMCountDownButton ()

@property (nonatomic, assign) NSInteger second;

@property (nonatomic, strong) NSString *originalTitle;
@property (nonatomic, strong) dispatch_source_t timer;

@end

@implementation LMCountDownButton

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        if (self.colorType) {
            [self setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
        }else
        {
             [self setTitleColor:[UIColor colorWithHexString:@"#FF7321"] forState:UIControlStateDisabled];
        }
       
    }
    
    return self;
}
-(void)setColorType:(UIColor *)colorType
{
    _colorType = colorType;
    if (self.colorType) {
               [self setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
           }else
           {
                [self setTitleColor:[UIColor colorWithHexString:@"#FF7321"] forState:UIControlStateDisabled];
           }
}
- (void)awakeFromNib {
    [super awakeFromNib];
    
    [self setTitleColor:UIColor.lightGrayColor forState:UIControlStateDisabled];
}

- (void)dealloc {
    
    NSLog(@"倒计时正常销毁！");
}

/// 开始倒计时
- (void)startCountDown {
    
    __weak typeof(self) weakSelf = self;
    
    self.originalTitle = self.currentTitle;
    self.second = totalSecond;
    self.enabled = NO;
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(self.timer,dispatch_time(DISPATCH_TIME_NOW, 0), 1 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(self.timer, ^{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            weakSelf.second--;
            
            if (weakSelf.second <= 0) {
                
                if (weakSelf.timer) dispatch_source_cancel(weakSelf.timer);
                weakSelf.timer = nil;
                weakSelf.enabled = YES;
                [weakSelf setTitle:@"重新发送" forState:UIControlStateNormal];
                return;
            }
            
            [weakSelf setTitle:[NSString stringWithFormat:@"重新发送(%ld)", (long)weakSelf.second] forState:UIControlStateNormal];
        });
        
    });
    
    dispatch_resume(self.timer);
}

@end
